<!-- 博客管理页面 -->
<template>
  <div class="blog-manage-container">
    <div class="page-header">
      <h2>博客管理</h2>
      <el-button type="primary" @click="$router.push('/blog/create')">写新博客</el-button>
    </div>

    <!-- 博客列表 -->
    <div class="blog-list">
      <el-table
        v-loading="loading"
        :data="blogs"
        style="width: 100%"
      >
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="{ row }">
            <el-link type="primary" @click="viewBlog(row.blogId)">{{ row.title }}</el-link>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column prop="views" label="浏览" width="100" align="center" />
        <el-table-column prop="likes" label="点赞" width="100" align="center" />
        <el-table-column prop="comments" label="评论" width="100" align="center" />

        <el-table-column prop="isPublished" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-tag :type="row.isPublished ? 'success' : 'info'">
              {{ row.isPublished ? '已发布' : '草稿' }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="250" align="center">
          <template #default="{ row }">
            <el-button-group>
              <el-button
                :type="row.isPublished ? 'warning' : 'success'"
                size="small"
                @click="togglePublishStatus(row)"
              >
                {{ row.isPublished ? '取消发布' : '发布' }}
              </el-button>
              <el-button
                type="primary"
                size="small"
                @click="editBlog(row.blogId)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="confirmDelete(row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <span>确定要删除博客"{{ selectedBlog?.title }}"吗？此操作不可恢复！</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="deleteBlog">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useBlogStore } from '@/stores/blog'
import { useAuthStore } from '@/store/auth'

const router = useRouter()
const blogStore = useBlogStore()
const userStore = useAuthStore()

// 状态变量
const loading = ref(false)
const blogs = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const deleteDialogVisible = ref(false)
const selectedBlog = ref(null)

// 获取博客列表
const fetchBlogs = async () => {
  try {
    loading.value = true
    const response = await blogStore.getAllBlogs({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      userId: userStore.user?.userId
    })
    blogs.value = response.content
    total.value = response.total
  } catch (error) {
    ElMessage.error('获取博客列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchBlogs()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchBlogs()
}

// 查看博客
const viewBlog = (blogId) => {
  router.push(`/blog/${blogId}`)
}

// 编辑博客
const editBlog = (blogId) => {
  router.push(`/blog/edit/${blogId}`)
}

// 发布/取消发布博客
const togglePublishStatus = async (blog) => {
  try {
    await blogStore.updatePublishStatus(blog.blogId, !blog.isPublished)
    ElMessage.success(blog.isPublished ? '博客已取消发布' : '博客已发布')
    await fetchBlogs()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 删除博客
const confirmDelete = (blog) => {
  selectedBlog.value = blog
  deleteDialogVisible.value = true
}

const deleteBlog = async () => {
  try {
    await blogStore.deleteBlog(selectedBlog.value.blogId)
    ElMessage.success('博客已删除')
    deleteDialogVisible.value = false
    await fetchBlogs()
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 页面加载时获取数据
onMounted(() => {
  fetchBlogs()
})
</script>

<style scoped>
.blog-manage-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.blog-list {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}
</style> 